package me.nereo.multi_image_selector.corpimg;


import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.RectF;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import me.nereo.multi_image_selector.R;

public class CropImgActivity extends AppCompatActivity implements View.OnClickListener {
    private TextView mCropBtn;
    private View mCropView;
    private ImageView mCropImg;
    private RelativeLayout mCropLayout;
    private Bitmap mCropBitmap;//要剪裁的图片
    private float downX, downY;
    private int top, left;
    private float oldSpacing;//第二个触点按下时两点间的距离
    private final int ZOOM = 1, DRAG = 0; //判断拖拽还是缩放
    private int state;//用拖拽还是缩放赋值
    private ImageView ivBack;
//    private float mTop,mBottom,mRight,mLeft;//图片
//    private float Top,Bottom,Right,Left;//框框

    /**
     * 记录两指中心点坐标
     *
     */
    private PointF mid = new PointF();
    private boolean isMain, isPointer;//第一个参数是否是主控点，没有就会在主控点先消失的时候，采用副控点的坐标产生不自然偏移，

    //第二个参数是是否只有一个控点
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme(R.style.MIS_NO_ACTIONBAR);
        setContentView(R.layout.mis_activity_crop_img);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(Color.BLACK);
        }

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        if(toolbar != null){
            setSupportActionBar(toolbar);
        }

        final ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }


        mCropBtn = (TextView) findViewById(R.id.corp_handle_btn);
        mCropBtn.setOnClickListener(this);
        mCropView = findViewById(R.id.crop_handler_select);
        mCropImg = (ImageView) findViewById(R.id.crop_handler_img);
        mCropLayout = (RelativeLayout) findViewById(R.id.crop_handler_layout);
        //要剪裁的图片
        String filePath = getIntent().getStringExtra("path");
        DisplayMetrics dm = getResources().getDisplayMetrics();
        Log.d(":::",dm.widthPixels+"  "+dm.heightPixels);
         mCropBitmap = decodeSampledBitmap(filePath,dm.widthPixels,dm.heightPixels);
//        mCropBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.tmw);
        mCropImg.setImageBitmap(mCropBitmap);
        //设置剪裁控件间的高度宽度
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int with = metrics.widthPixels-Dp2Px(this.getApplicationContext(),20);
        ViewGroup.LayoutParams layoutParams = mCropView.getLayoutParams();
        layoutParams.height =with;
                layoutParams.width=with;
        mCropView.setLayoutParams(layoutParams);

        //ImageView设置监听，单点移动，双点缩放
        mCropImg.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction() & motionEvent.getActionMasked()) {
                    case MotionEvent.ACTION_POINTER_DOWN:
                        //次要点被点击
                        oldSpacing = spacing(motionEvent);
                        if (oldSpacing > 10f) {
                            isPointer = false;
                            isMain = false;
                            state = ZOOM;
                            midPoint(mid, motionEvent);
                        }
                        break;
                    case MotionEvent.ACTION_POINTER_UP:
                        //次要点松开
                        Log.d("CropHandlerActivity", "ACTION_POINTER_UP");
                        isPointer = true;
                        if (isPointer && isMain) {
                            isPointer = false;
                            isMain = false;
                            state = DRAG;
                            oldSpacing = 1f;
                        }
                        break;
                    case MotionEvent.ACTION_DOWN:
                        downX = motionEvent.getX();
                        downY = motionEvent.getY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        Matrix matrix = mCropImg.getImageMatrix();
                        if (state == DRAG) {
                            //拖拽
                            float translateX= motionEvent.getX() - downX;
                            float translateY =  motionEvent.getY() - downY;

                            matrix.postTranslate(translateX,translateY);
                            downX = motionEvent.getX();
                            downY = motionEvent.getY();
                        } else if (state == ZOOM && !isPointer && !isMain) {
                            //放大缩小
                            float newSpacing = spacing(motionEvent);
                            float scale = newSpacing / oldSpacing;
                            matrix.postScale(scale, scale, mid.x, mid.y);
                            oldSpacing = newSpacing;
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        isMain = true;
                        if (isPointer && isMain) {
                            isPointer = false;
                            isMain = false;
                            state = DRAG;
                            oldSpacing = 1f;
                        }
                        break;
                }
                mCropImg.invalidate();
                return true;
            }
        });

    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                setResult(RESULT_CANCELED);
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
    /**
     * 初始化图片的显示
     * 这个onWindowFocusChanged指的是这个Activity得到或者失去焦点的时候 就会call。。,对于getWtih()=0的情况，可以处理，对以后很有用
     */
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            int layoutWidth = mCropLayout.getWidth();
            int layoutHeight = mCropLayout.getHeight();
            int imgWidth = mCropBitmap.getWidth();
            int imgHeight = mCropBitmap.getHeight();
            int selectWidth = mCropView.getWidth();
            int selectHeight = mCropView.getHeight();
//            Top = mCropView.getTop();//得到框的坐标
//            Bottom = mCropView.getBottom();
//            Right = mCropView.getRight();
//            Left = mCropView.getLeft();

            //缩放比例
            float scaleNum;

            //将要裁剪的图片长宽高做对比， 将较小的一方做等比缩放成裁剪框大小
            if (imgWidth < imgHeight) {
                scaleNum = (selectWidth * 1.0f) / (imgWidth * 1.0f);
                imgHeight = (int) (scaleNum * imgHeight);
                imgWidth = selectWidth;
            } else {
                scaleNum = (selectHeight * 1.0f) / (imgHeight * 1.0f);
                imgWidth = (int) (scaleNum * imgWidth);
                imgHeight = selectHeight;
            }
            Matrix matrix = new Matrix();
            matrix.postScale(scaleNum, scaleNum);
            //平移距离
            matrix.postTranslate((layoutWidth - imgWidth) / 2, (layoutHeight - imgHeight) / 2);

            top = (layoutHeight - selectHeight) / 2;
            left = (layoutWidth - selectWidth) / 2;

            //设置缩放类型为 矩阵
            mCropImg.setScaleType(ImageView.ScaleType.MATRIX);
            RectF r= new RectF();//得到图片的初始坐标
            matrix.mapRect(r);
//            mTop =r.top;
//            mBottom =r.bottom;
//            mRight =r.right;
//            mLeft = r.left;
            mCropImg.setImageMatrix(matrix);
            mCropImg.setImageBitmap(mCropBitmap);

        }
    }

    @Override
    public void onClick(View view) {
        int i = view.getId();
        if (i == R.id.corp_handle_btn) {
            Bitmap bitmap = getBitMap();//剪裁
            String path = saveBitmap(bitmap);//保存
            if (path == null || TextUtils.isEmpty(path)) {
                Log.e("CropImgActivity", "空的");
                return;
            }
            Intent intent = new Intent();
            intent.putExtra("path",path);

            setResult(RESULT_OK, intent);
            finish();
//                CropShoActivity.startThis(this, path);

        }

    }

    /**
     * 获取sdcard路径
     *
     * @return
     */
    private String getSDCardPath() {
        File sdcardDir = null;
        // 判断SDCard是否存在
        boolean sdcardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
        if (sdcardExist) {
            sdcardDir = Environment.getExternalStorageDirectory();
        }
        return sdcardDir.toString();
    }

    /**
     * 获得缓存应用专属缓存目录
     */
    private String getCacheDirctory() {
        File appCacheDir = getExternalCacheDir();

        if (appCacheDir == null) {
            Log.e("getCacheDirectory", "getCacheDirectory fail ,the reason is mobile phone unknown exception !");
        } else {
            if (!appCacheDir.exists() && !appCacheDir.mkdirs()) {
                Log.e("getCacheDirectory", "getCacheDirectory fail ,the reason is make directory fail !");
            }
        }
        return appCacheDir.getAbsolutePath();
    }

    /**
     * 保存图片
     *
     * @param bitmap
     * @return
     */
    private String saveBitmap(Bitmap bitmap) {
        FileOutputStream fos = null;
        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CANADA).format(new Date());
        String fileName = "myCropTemp_" + timeStamp + ".jpeg";

        try {
            String filePaths = getCacheDirctory();
//            Log.e("CropImgActivity", filePaths);
            File tempFiles = new File(filePaths);
            if (!tempFiles.exists()) {
                tempFiles.mkdirs();
            }
            //创建图片文件
            File file = new File(filePaths + File.separator + fileName);

            if (!file.exists()) {
                file.createNewFile();
            }
            fos = new FileOutputStream(file);
            if (fos != null) {
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            }
            fos.close();
            return file.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }

    }

    /**
     * 多控点时，计算两指中心点的坐标
     *
     * @param mid
     * @param motionEvent
     */
    private void midPoint(PointF mid, MotionEvent motionEvent) {
        float x = motionEvent.getX(0) + motionEvent.getX(1);
        float y = motionEvent.getY(0) + motionEvent.getY(1);
        mid.set(x / 2, y / 2);
    }

    /**
     * 多控点时，计算最先放下的两指距离
     */
    private float spacing(MotionEvent motionEvent) {
        float x = motionEvent.getX(0) - motionEvent.getX(1);
        float y = motionEvent.getY(0) - motionEvent.getY(1);
        return (float) Math.sqrt(x * x + y * y);
    }

    /**
     * 获取剪裁框内截图
     *
     * @return
     */
    public Bitmap getBitMap() {
        //获取截屏
        mCropLayout.setDrawingCacheEnabled(true);
        mCropLayout.buildDrawingCache();
        int borderWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics());
        Bitmap finalBitmap = Bitmap.createBitmap(mCropLayout.getDrawingCache(),
                left + borderWidth,
                top + borderWidth,
                mCropView.getWidth() - 2 * borderWidth,
                mCropView.getHeight() - 2 * borderWidth);
        //释放资源
        mCropLayout.destroyDrawingCache();

        return finalBitmap;
    }
    /**
     * dp转换成px,代码写的是像素,而XML中写的是单位密度
     * @param context
     * @param dp
     * @return
     */
    public static int Dp2Px(Context context, float dp) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }

//    public float getTranSlateX(float v) {
//        if(v>=0){//向右拖
//           if(mRight+1<=Right){
//               return v;
//           }else {
//               return Right
//           }
//        }else {//向左拖
//
//        }
//
//    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mCropBitmap!=null){
        mCropBitmap.recycle();
        }
    }


    public static int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            if (width > height) {
                inSampleSize = Math.round((float)height / (float)reqHeight);
            } else {
                inSampleSize = Math.round((float)width / (float)reqWidth);
            }
        }
        return inSampleSize;
    }



    public static Bitmap decodeSampledBitmap(  String path,
                                                         int reqWidth, int reqHeight) {

        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(path, options);
    }
}
